package com.xn.myyxcampus.fragment;

import java.io.IOException;
import java.util.HashMap;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.LogUtils;
import com.xn.myyxcampus.MainActivity;
import com.xn.myyxcampus.NewsDetailActivity;
import com.xn.myyxcampus.R;
import com.xn.myyxcampus.adapter.NewsListViewAdapter;
import com.xn.myyxcampus.bean.NewsList;
import com.xn.myyxcampus.http.URLHelper;
import com.xn.myyxcampus.http.URLs;
import com.xn.myyxcampus.utils.AnimUtils;
import com.xn.myyxcampus.utils.JacksonUtils;
import com.xn.myyxcampus.utils.ToastUtils;
import com.xn.myyxcampus.view.PullDownView;
import com.xn.myyxcampus.view.PullDownView.OnPullDownListener;

public class NewsFragment extends BaseFragment implements OnPullDownListener,
		OnClickListener, OnItemClickListener {
	/**
	 * loading
	 */
	private ImageView iv_Loading;
	/**
	 * 该fragment的布局
	 */
	private View view;
	/**
	 * 现实侧滑菜单
	 */
	private ImageView iv_showMenu;

	private PullDownView pull_down_view;
	private ListView mListView;
	private NewsListViewAdapter newsListAdapter = new NewsListViewAdapter();

	private static final int WHAT_DID_LOAD_DATA = 0;
	/** Handler What更新数据完毕 **/
	private static final int WHAT_DID_REFRESH = 1;
	/** Handler What更多数据完毕 **/
	private static final int WHAT_DID_MORE = 2;
	/** Handler What加载数据失败 **/
	private static final int WHAT_DID_FAILED = 3;
	/**
	 * 传过来的新闻数据
	 */
	private NewsList newsList;
	/** 加载更多页码，默认为第二页，当刷新时重置为2，当一次加载更多完成*时加1 */
	private int currentPage = 2;

	@Override
	public View initView(LayoutInflater inflater) {
		// TODO Auto-generated method stub
		view = inflater.inflate(R.layout.news, null);

		iv_showMenu = (ImageView) view.findViewById(R.id.iv_showMenu);
		iv_Loading = (ImageView) view.findViewById(R.id.iv_newsLoading);
		pull_down_view = (PullDownView) view.findViewById(R.id.pull_down_view);

		pull_down_view.setOnPullDownListener(this);
		mListView = pull_down_view.getListView();
		mListView.setOnItemClickListener(this);

		mListView.setVisibility(View.GONE);
		mListView.setAdapter(newsListAdapter);
		// 设置可以自动获取更多 滑到最后一个自动获取 改成false将禁用自动获取更多
		pull_down_view.enableAutoFetchMore(false, 1);

		animationDrawable = (AnimationDrawable) iv_Loading.getBackground();
		animationDrawable.start();
		iv_showMenu.setOnClickListener(NewsFragment.this);
		return view;
	}

	private HttpUtils httpUtil = new HttpUtils();

	@Override
	public void initData(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		httpUtil.send(HttpRequest.HttpMethod.GET,
				URLHelper.getURL(URLs.NEWS_LOAD, null),
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// TODO Auto-generated method stub
						ToastUtils.showToast("网络异常..淡定~~");
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						// TODO Auto-generated method stub
						loadData(arg0.result, WHAT_DID_LOAD_DATA);
						LogUtils.i(arg0.result);
						LogUtils.i("initData" + arg0.statusCode + "");

					}
				});
	}

	private void loadData(String result, int action) {
		try {
			ObjectMapper mapper = new ObjectMapper();
			HashMap<String, Object> map = (HashMap<String, Object>) mapper
					.readValue(result, HashMap.class);
			int response = (Integer) map.get("response");
			LogUtils.i("response:" + response);
			switch (action) {
			case WHAT_DID_LOAD_DATA:
				newsList = JacksonUtils.jsonToBean(result, NewsList.class);
				mListView.setVisibility(View.VISIBLE);
				Animation animation = AnimationUtils.loadAnimation(ct,
						R.anim.list_anim);
				LayoutAnimationController controller = new LayoutAnimationController(
						animation, 10);
				mListView.setLayoutAnimation(controller);
				animationDrawable.stop();
				iv_Loading.setVisibility(View.GONE);
				currentPage = 2;
				break;
			case WHAT_DID_MORE:
				if (1 == response) {
					NewsList moreNews = JacksonUtils.jsonToBean(result,
							NewsList.class);
					if (moreNews.getList().size() > 0) {
						newsList.getList().addAll(moreNews.getList());
					}
				} else {
					ToastUtils.showToast("没有更多数据了哦！~~~");
				}
				currentPage++;
				break;
			case WHAT_DID_REFRESH:
				newsList.getList().clear();
				newsList = JacksonUtils.jsonToBean(result, NewsList.class);
				currentPage = 2;
				break;
			case WHAT_DID_FAILED:
				break;
			}
			newsListAdapter.loadData(newsList);
			newsListAdapter.notifyDataSetChanged();
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		LogUtils.i("onRefresh..onRefresh");
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					Thread.sleep(2000);
					pull_down_view.RefreshComplete();
					httpUtil.send(HttpRequest.HttpMethod.GET,
							URLHelper.getURL(URLs.NEWS_LOAD, null),
							new RequestCallBack<String>() {
								@Override
								public void onFailure(HttpException arg0,
										String arg1) {
									// TODO Auto-generated method stub
									ToastUtils.showToast("网络访问异常..淡定~~");
								}

								@Override
								public void onSuccess(ResponseInfo<String> arg0) {
									// TODO Auto-generated method stub
									LogUtils.i("statusCode" + arg0.statusCode);
									LogUtils.i("result" + arg0.result);
									loadData(arg0.result, WHAT_DID_REFRESH);
								}
							});
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	@Override
	public void onMore() {
		// TODO Auto-generated method stub
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				pull_down_view.notifyDidMore();
				NameValuePair page_pair = new BasicNameValuePair("page",
						currentPage + "");
				httpUtil.send(HttpRequest.HttpMethod.GET,
						URLHelper.getURL(URLs.NEWS_MORE, page_pair),
						new RequestCallBack<String>() {
							@Override
							public void onFailure(HttpException arg0,
									String arg1) {
								// TODO Auto-generated method stub
								ToastUtils.showToast("网络访问异常..淡定~~");
							}

							@Override
							public void onSuccess(ResponseInfo<String> arg0) {
								// TODO Auto-generated method stub
								LogUtils.i("statusCode" + arg0.statusCode);
								loadData(arg0.result, WHAT_DID_MORE);
								LogUtils.i(currentPage + "" + arg0.result);
							}
						});
			}
		}).start();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_showMenu:
			showLeft();
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		String newsID = newsList.getList().get(position).getId();
		Intent intent = new Intent((MainActivity)getActivity(), NewsDetailActivity.class);
		intent.putExtra("newsID", newsID);
		startActivity(intent);
		AnimUtils.scaleIn((MainActivity)getActivity());
	}

}
